package com.itzmn.java.javase.collections;

import com.itzmn.java.javase.collections.interfaces.QiYeDeque;

import javax.swing.plaf.synth.SynthTextAreaUI;
import java.util.NoSuchElementException;
import java.util.concurrent.DelayQueue;

/**
 * @Author: 张梦楠
 * @Date: 2018/12/6 18:33
 * 简书：https://www.jianshu.com/u/d611be10d1a6
 * 码云：https://gitee.com/zhangqiye
 * @Description:
 */
public class QiYeArrayDeque<T> implements QiYeDeque<T> {

    private Object[] data;

    private int head;
    private int end;
    private static final int DEFAULT_MIN_SIZE = 8;

    private QiYeArrayDeque(){
        data = new Object[16];
    }
    private QiYeArrayDeque(int size){
        data = new Object[check(size)];
    }
    private int check(int size) {
        if (size > DEFAULT_MIN_SIZE){
            return size;
        }
        return DEFAULT_MIN_SIZE;
    }


    @Override
    public T getFirst() {
        T datum = (T) data[head];
        if (datum == null){
            throw new NoSuchElementException();
        }
        return datum;
    }

    @Override
    public T getLast() {
        T datum = (T) data[end];
        if (datum == null){
            throw new NoSuchElementException();
        }
        return datum;
    }

    @Override
    public T peekFirst() {
        return (T) data[head];
    }

    @Override
    public T peekLast() {
        return (T) data[end];
    }

    @Override
    public void addFirst(T e) {

        data[head = (head-1) & (data.length-1)] = e;
        if (head == end){
            doubleSize();
        }

    }

    private void doubleSize() {
        int newSize = data.length << 1;
        int h = head;
        int m = data.length - head;
        Object[] objects = new Object[newSize];
        System.arraycopy(data,head,objects,0,m);
        System.arraycopy(data,0,objects,m,end);
        data = objects;
    }

    @Override
    public void addLast(T e) {
        data[end = (end+1) & (data.length-1)] = e;
        if (end == head){
            doubleSize();
        }
    }
    @Override
    public boolean offerFirst(T e) {
        return false;
    }

    @Override
    public boolean offerLast(T e) {
        return false;
    }

    @Override
    public T removeFist() {
        return null;
    }

    @Override
    public T removeLast() {
        return null;
    }

    @Override
    public T pollFirst() {
        return null;
    }

    @Override
    public T pollLast() {
        return null;
    }
}
